import React from "react";
import {Upload, message} from 'antd';
import {AliyunOss} from '@/services/alioss';

export default class AliyunOssUpdate extends React.Component {
  state = {
    OSSData: {},
  };

  /**
   * 组价挂载完成后 进行初始化 获取oss
   * @returns {Promise<void>}
   */
  async componentDidMount() {
    await this.init();
  }

  /**
   * 初始化 获取oss上传签名
   * @returns {Promise<void>}
   */
  init = async () => {
    try {
      const OSSData = await AliyunOss();
      this.setState({
        OSSData,
      });
    } catch (error) {
      message.error(error);
    }
  };

  /**
   * 文件上传过程中触发的函数，直到上传成功
   * @param fileList
   */
  onChange = ({ file }) => {
    if (file.status === 'done') {
      this.props.setIconKey(file.key)
    }
  };

  /**
   * 额外的上传参数
   * @param file
   * @returns {{OSSAccessKeyId: string, Signature: *, key, policy: (string|Protocol.Emulation.VirtualTimePolicy|*)}}
   */
  getExtraData = file => {
    const { OSSData } = this.state;
    return {
      key: file.key,
      OSSAccessKeyId: OSSData.accessid,
      policy: OSSData.policy,
      Signature: OSSData.signature,
    };
  };

  /**
   * 选择文件之后 上传文件之前 执行回调
   * @param file
   * @returns {Promise<*>}
   */
  beforeUpload = async file => {
    const { OSSData } = this.state;
    const expire = OSSData.expire * 1000;

    if (expire < Date.now()) {
      await this.init();
    }
    const dir = "react/";
    const suffix = file.name.slice(file.name.lastIndexOf('.'));
    const filename = Date.now()  + suffix;
    file.key = OSSData.dir + dir +  filename
    file.url = OSSData.host + OSSData.dir + dir + filename;
    return file;
  };

  render() {
    const { value,accept } = this.props;
    const props = {
      accept: accept || '',
      name: 'file',
      fileList: value,
      maxCount:1,
      action: this.state.OSSData.host,
      onChange: this.onChange,
      data: this.getExtraData,
      beforeUpload: this.beforeUpload,
      listType: this.props.listType === undefined ? "picture" : this.props.listType
    };
    return (
      <Upload {...props} >
        {
          this.props.children
        }
      </Upload>
    );
  }
}


